 <!--
 * @Description  : 预览Excel
 * @Autor        : 杜康
 * @Date         : 2023-03-31 11:09:30 +0800
 * @LastEditors  : 杜康
 * @LastEditTime : 2023-04-13 16:31:10 +0800
-->
<template>
  <div class="office">
    <div class="office-btn">
      <el-radio-group v-model="fileType">
        <el-radio-button label="online">在线</el-radio-button>
        <el-radio-button label="local">本地</el-radio-button>
      </el-radio-group>
      <div v-if="fileType === 'online'" class="office-btn-online">
        <el-input v-model="excel" placeholder="请输入要预览的在线Excel路径" />
        <el-button class="ml15" type="primary">预览</el-button>
      </div>
      <div v-if="fileType === 'local'" class="office-btn-file ml15">
        <el-upload v-model="localFile" action="" :before-upload="beforeUpload" :file-list="fileList" :limit="1">
          <el-button type="primary">请选择Excel</el-button>
        </el-upload>
      </div>
    </div>
    <div class="office-preview">
      <VueOfficeExcel v-if="fileType === 'online'" style="height: 100vh;" :src="excel" accept=".xlsx" @rendered="rendered" />
      <VueOfficeExcel v-if="fileType === 'local'" style="height: 100vh;" :src="localFile" accept=".xlsx" />
    </div>
  </div>
</template>

<script setup>
import { reactive, ref, nextTick } from "vue";
//引入VueOfficeExcel组件
import VueOfficeExcel from "@vue-office/excel";
//引入相关样式
import "@vue-office/excel/lib/index.css";

// 文档类型
const fileType = ref(`online`);

// 文档数据源
let excel = ref(`http://static.shanhuxueyuan.com/demo/excel.xlsx`);

// 回调函数
const rendered = () => {
  console.log("渲染完成");
};

// 本地文件
let localFile = ref("");

let fileList = reactive([]);

const beforeUpload = (file) => {
  const reader = new FileReader();
  reader.readAsArrayBuffer(file);
  reader.onload = async (loadEvent) => {
    let arrayBuffer = loadEvent?.target?.result;
    nextTick(() => {
      localFile.value = arrayBuffer;
    });
  };
  return false;
};
</script>
